package com.runfast.waimai.web.controller.Driver_controller;

import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.paotui.dao.model.RunfastDeliverCost;
import com.runfast.paotui.dao.model.RunfastLoginRecord;
import com.runfast.paotui.dao.model.RunfastShopper;
import com.runfast.paotui.service.RunfastDeliverCostService;
import com.runfast.paotui.service.RunfastLoginRecordService;
import com.runfast.paotui.service.RunfastShopperService;


import com.runfast.waimai.dao.model.CSTest;
import com.runfast.waimai.dao.model.RunfastSmsSendrecord;

import com.runfast.waimai.service.RunfastSmsSendrecordService;
import com.runfast.waimai.util.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;


@Controller
@RequestMapping("/driver/*")
public class DriverLoginController extends DriverBaseController{
	//登录 手机短信验证  找回密码，发送验证码
	@Resource
	private RunfastShopperService shopperService;
	//runfast_shoppingTrolley 购物车
	@Resource
	private RunfastSmsSendrecordService smsSendRecordService;
	//短信发送记录RunfastSmsSendrecord
	@Resource
	private RunfastDeliverCostService deliverCostService;
	//RunfastDeliverCost 配送费用
	@Resource
	RunfastLoginRecordService runfastLoginRecordService; //新加的登陸表


	@Autowired
	private RedisTemplate redisTemplate;
//	RunfastLoginRecord shop=new RunfastLoginRecord();
	/*@Autowired
	private RedisOperationsSessionRepository repository;*/

	@InitBinder//限定只有传参包含Application属性时才执行添加此操作
	public void initBinder(WebDataBinder binder) {
		//binder.setValidator(validator);
		///注册转换器
		binder.registerCustomEditor(Date.class, new MyCustomDateEditor());
	}
//	/**
//	 * 检查app版本
//	 *
//	 * @param version
//	 * @return
//	 */
//	@PostMapping("/checkVersion")
//	public @ResponseBody ModelMap checkVersion(@RequestParam int version) {
//		ModelMap model=new ModelMap();
//
//		if (serverVersion == null || StringUtils.isBlank(serverUrl))
//			return Result.fail(ResultCode.FAIL, "app版本更新配置信息为空");
//
//		if (version < serverVersion) {
//			Map<String, Object> update = new HashMap<>();
//			update.put("serverVersion", serverVersion);
//			update.put("serverDescription", serverDescription);
//			update.put("serverUrl", serverUrl);
//
//			return Result.ok("", update);
//		} else return Result.ok("已经是最新版本");
//
//	}
	/*
	* 验证码验证
	*
	* */
	@PostMapping("loginmsg")
	public @ResponseBody ModelMap loginmsg(String number,HttpSession session){
		//手机号不能为空
		ModelMap model=new ModelMap();
		RunfastShopper number1=shopperService.findByNumeber(number);
		if(number1 !=null){
		Random random=new Random();
		String result="";
		for (int i = 0; i <6 ; i++) {
			result +=random.nextInt(10);

		}
		session.setAttribute("result" ,result);
		model.put("result",result);


		}
		else { model.put("msg","手机号不能为空");}
		return  model;
	}
	@PostMapping("loginmsg1")
	public @ResponseBody ModelMap loginmsg1(String number,String result,String password, HttpSession session){ //手机号不能为空 msg 为发送过来的验证码

		ModelMap model=new ModelMap();
		RunfastShopper number1=shopperService.findByNumeber(number);
		if(number1 !=null){
		//	System.out.println(request.getSession().getAttribute("result"));
			if(result.equals(session.getAttribute("result"))){
				model.put("suceess","验证码相同");
				if(DigestUtils.md5Hex(password).equals(number1.getPassword())){
					model.put("msg","密码相同");
				}else {model.put("msg","密码不正确");}
			}else {
				model.put("suceess","验证码有误");
				model.put("sss",session.getAttribute("result"));
			}
		}

		return  model;
	}
	/**
	 * 登录
	 * @param password
	 * @return
	 */
	@PostMapping(value="login")//验证
	public @ResponseBody ModelMap login(@RequestParam(value="userName",required=false) String userName, //用户名
			@RequestParam(value="password",required=false) String password, //密码
			@RequestParam(value="vercode",required=false) Integer vercode,//安卓版本
			@RequestParam(value="bdchannelId",required=false) String bdchannelId, //推送渠道ID
			@RequestParam(value="bduserId",required=false) String bduserId, //推送用户ID
			@RequestParam(value="pushType",required=false) Integer pushType, //push类型对应的用户标识类型
			@RequestParam(value="otherId",required=false) String otherId, // push类型对应的用户标识
			@RequestParam(value="bptype",required=false,defaultValue="0") Integer bptype, //0或空  Android用户  1 ios用户
			@RequestParam(value="alias",required=false) String alias, ///唯一识别
			HttpSession session){
		String a = "abcdefghijklmn";
	ModelMap model = new ModelMap();
	//	String sessionid=session.getId();

		if(ComUtil.isEmpty(userName)||ComUtil.isEmpty(password)){
			model.put("success", false);
			model.put("msg", "用户名或密码不能为空！");
			return model;
		}

		RunfastShopper shopper = shopperService.findByUserName(userName);

		if(shopper==null||!password.equals(shopper.getPassword())){
			model.put("success", false);
			model.put("msg", "用户名或密码错误！");
			return model;
		}
		if(shopper.getStatus()!=null && shopper.getStatus()==-1){
			model.put("success", false);
			model.put("msg", "登录失败，您的帐号已被冻结！");
			return model;
		}
		
		Map<String,Object> obj = null;
		if(bptype!=null && bptype==1){//ios版本判断
			String verFile = session.getServletContext().getRealPath("/iosdver.txt");
			obj = checkIOSVersion(vercode,verFile);
		}else{///android版本判断
			String verFile = session.getServletContext().getRealPath("/dver.txt");
			obj = checkAndroidVersion(vercode,verFile);
		}
		
		if(obj!=null && (Boolean)obj.get("isupdate")){
			//有新版本更新
			String msg = "您的版本过低，请更新版本后再登录";
			if(bptype!=null && bptype==1){///ios提示
				model.put("update", true);
				String upmsg = (String) obj.get("msg");
				if(!ComUtil.isEmpty(upmsg)){
					msg += "\n新版本更新内容如下：\n"  + upmsg;
				}
			}else{//android的提示ʾ
				String apkName = (String) obj.get("apkName");
				if(!ComUtil.isEmpty(apkName)){
					model.put("update", true);
					model.put("apkName", apkName);
				}
				String upmsg = (String) obj.get("msg");
				if(!ComUtil.isEmpty(upmsg)){
					msg += "\n新版本更新内容如下：\n" + upmsg;
				}
			}
			model.put("msg", msg);
			model.put("success", false);
		}else{
			List<RunfastDeliverCost> list = deliverCostService.findAll();
			if(shopper.getCreditLevelid()!=null){
			RunfastDeliverCost dc = deliverCostService.get(shopper.getCreditLevelid());
			if(dc!=null){
			model.put("startTimeDay1", dc.getStartTimeDay1());//c1计费开始时间
			model.put("endTimeDay1", dc.getEndTimeDay1());//c1计费结束时间
			model.put("startTimeNight2", dc.getStartTimeNight2());//c2计费开始时间
			model.put("endTimeNight2", dc.getEndTimeNight2());//c2计费结束时间
		}
			}
			//alias 别名不为空，执行 更新为空update 表名 set alias=null where alias=#{alias} 原始版本
			//应该有点问题
			if(alias!=null){shopperService.updateAlias(shopper);}
			//保存百度推送信息
			if(!ComUtil.isEmpty(bdchannelId) && !ComUtil.isEmpty(bduserId)|| !ComUtil.isEmpty(otherId)){
				shopper.setBptype(bptype);
				shopper.setBdchannelId(bdchannelId);
				shopper.setBduserId(bduserId);
				shopper.setOtherId(otherId);
				shopper.setPushType(pushType);
				shopper.setAlias(alias);
				shopperService.update(shopper);
			}else{
			shopper.setPushType(pushType);
			shopper.setBptype(bptype);
			shopper.setAlias(alias);
			shopperService.update(shopper);
			}
	//		System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+shopper);


	//		shopper.setPassword(null);
			if(shopper.getWorking()==null){
				shopper.setWorking(1);//1为工作，2为其它休息

			}
			String token1 = AESUtil.encrypt(String.valueOf(shopper.getId()), a);//骑手id和密码生成token1
			shopper.setToken(token1);//设置token1
//			RunfastLoginRecord shop=runfastLoginRecordService.getshopperLoginmsg(shopper.getId());
			if(shopper.getId()!=null){
				//给在线的全都退出，再重新生成登陸记录
				List<RunfastLoginRecord> runfastLoginRecord=runfastLoginRecordService.getshopperLoginmsg(shopper.getId());
				if(runfastLoginRecord.size()>0) {
					for (RunfastLoginRecord s : runfastLoginRecord) {
						s.setLogouttime(new Date());
						s.setAlias(null);
						runfastLoginRecordService.updateByPrimaryKeySelective(s);
					}
					((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().removeAttribute(Constant.APP_DRIVER_SESSION);/*配送员*/
				}

				RunfastLoginRecord shop=new RunfastLoginRecord();
//			if(null==shop){
//			shopperService.addtoken(shopper);//更新到数据库
			shop.setAccountid(shopper.getId()); //设置骑手ID
			shop.setLogintime(new Date());//设置时间
			shop.setAccounttype(2);//设置骑手类型
			shop.setAlias(alias);//设置识别码
				runfastLoginRecordService.insertSelective(shop); //把数据添加进去

				}else {
				model.put("success",true);
				model.put("msg","骑手登陸失败");
			}
//
//			model.put("runfastLoginRecord_id",shop.getId());//退出的时候要用
	//		CSTest.Token.setDescription(token1);//将token 保存在梅举内
			session.setAttribute(Constant.APP_DRIVER_SESSION, shopper);
			model.put("token", token1);//返回前端
			model.put("appuser", shopper);
			model.put("success", true);
			model.put("msg", "登录成功");
		}
		
		return model;
	}
	@PostMapping("checkVersion")
	@ResponseBody
	public Result checkVersion(@RequestParam Integer vercode) {
		 Integer serverVersion=23;
		 String apkName="user-20180505";
		 String  serverDescription="app-driver-local-23";
		  String  serverUrl="http://image.gxptkc.com/app-driver-local-23.apk";


		if (serverVersion == null || StringUtils.isBlank(serverUrl))
			return Result.fail(ResultCode.FAIL, "app版本更新配置信息为空");

		if (vercode < serverVersion) {
			Map<String, Object> update = new HashMap<>();
			update.put("serverVersion", serverVersion);
			update.put("serverDescription", serverDescription);
			update.put("serverUrl", serverUrl);

			return Result.ok("", update);
		} else return Result.ok("已经是最新版本");

	}

	@PostMapping("checkVersion1")//版本判断
	@ResponseBody
	public ModelMap checkVersion(@RequestParam(value="vercode",required=false) Integer vercode,
								 @RequestParam(value="bptype",required=false,defaultValue = "0") Integer bptype, HttpSession session){
		ModelMap model = new ModelMap();


		Map<String,Object> obj = null;
		String downloadUrl = "";
		if(bptype!=null && bptype==1){///ios版本判断
			String verFile = session.getServletContext().getRealPath("/iosdver.txt");
			obj = checkVersion(vercode,verFile);
		}else{///android版本判断
			String verFile = session.getServletContext().getRealPath("/dver.txt");
			obj = checkVersion(vercode,verFile); //安卓版本
		}


		if(obj!=null && (Boolean)obj.get("isupdate")) {
			//有新版本更新
			String msg = "您的版本过低，请更新版本后再登录";
			String apkName = (String) obj.get("apkName");
			if (!ComUtil.isEmpty(apkName)) {
				model.put("update", true);
				model.put("apkName", apkName);
				if(1==bptype){
                    model.put("downloadUrl","https://www.fir.im/qishou");
                }else{
                    model.put("downloadUrl","http://image.gxptkc.com/apk/"+apkName);
                }

			}
			String upmsg = (String) obj.get("msg");
			if (!ComUtil.isEmpty(upmsg)) {
				msg += "\n新版本更新内容如下：\n" + upmsg;
			}
			model.put("msg", msg);
			model.put("success", true);

		}else{
			model.put("update", false);
			model.put("msg", "已经是最新版本");
			model.put("success", true);
		}
		return model;
	}

	@PostMapping("logout") //退出时，更新时model.put 先返回，要不然执行invalidate会报错
	public @ResponseBody ModelMap logout(/*SessionStatus status*/HttpSession session,String alias,String token){
		//Integer id 为登陸账号的序列号
	//	RunfastLoginRecord runfastLoginRecord=runfastLoginRecordService.findid(id);
		ModelMap model = new ModelMap();

		RunfastShopper shopper=super.getLoginShopper(token);

		shopper.setToken(null);
//		model.put("sss",shopper);
	//=shopperService.get(Integer.parseInt(id));
	//	RunfastLoginRecord shopper1=runfastLoginRecordService.getshopperLoginmsg(Integer.parseInt(id));
//	RunfastShopper shopper=shopperService.get(4);
		if(null !=shopper.getAlias()){
			shopperService.updateAlias(shopper);
	//		runfastLoginRecord.setLogouttime(new Date());//设置退出时间
//			RunfastLoginRecord shop=runfastLoginRecordService.getshopperLoginmsg(shopper.getId());
//			if(shop!=null){
//			shop.setLogouttime(new Date());
//
//			runfastLoginRecordService.updateByPrimaryKeySelective(shop);}
		//	model.put("shop的信息",runfastLoginRecord);
			model.put("msg", new Date()+"成功退出");
			model.put("success",true);
//		session.removeAttribute(String.valueOf(shopper.getId()));
//		session.invalidate();

		}
		else{
			model.put("msg", "还没有登陸");
			model.put("success",false);



		}
		return model;
	}
	
	/**
	 * 找回密码，发送验证码
	 * @param mobile
	 */
	@PostMapping(value="findpwd")//
	public @ResponseBody ModelMap findpwd(@RequestParam(value="mobile",required=false) String mobile,
			HttpSession session, HttpServletRequest request){
		ModelMap model = new ModelMap();
		
		if(ComUtil.isEmpty(mobile)){
			model.put("success", false);
			model.put("msg", "手机号码不能为空");
			return model;
		}
		RunfastShopper shopper = shopperService.findByNumeber(mobile);
		if(shopper.equals(null)&&shopper.getMunber()!=null){
			model.put("success", false);
			model.put("msg", "该号码尚未注册");
			return model;
		}
		//判断是否频繁发送短信
		RunfastSmsSendrecord record = smsSendRecordService.findNewRecord(mobile, 2,null);
		if(record!=null&&record.getSendtime()!=null
				&&(System.currentTimeMillis()-record.getSendtime().getTime()<=60000)){
			model.put("success", false);
			model.put("msg", "不能频繁发送短信！");
			return model;
		}
		//生成验证码
		String xcode = MyUtil.randomNumber(4);
		String content ="找回密码验证码："+xcode;
		//保存验证码记录
		record = new RunfastSmsSendrecord();
		record.setSmstype(2);
		record.setPhone(mobile);
		record.setXcode(xcode);
		record.setIpaddr(request.getRemoteAddr());
		record.setMsg(content);
		record.setSendtime(new Date());
		smsSendRecordService.insert(record);
		ModelMap sendMsg = SingleSendSms.sendMsg(mobile, "{'code':'" + xcode + "'}", "SMS_17020084");
		if(!(boolean)sendMsg.get("success")){
			sendMsg.put("msg",sendMsg.get("message"));
			return sendMsg;
		}
		System.out.println("骑手找回密码："+content);
		///发送短信　TODO
		model.put("success", true);
		model.put("msg", "验证码在发送到手机上，请注意查看");
		return model;
	}
	/**
	 *  找回密码，发送用户密码到用户手机上
	 * @param mobile
	 */
	@PostMapping(value="sendpwd")///验证
	public @ResponseBody ModelMap sendpwd(@RequestParam(value="mobile",required=false) String mobile,
			@RequestParam(value="xcode",required=false) String xcode,
			HttpSession session, HttpServletRequest request){
		ModelMap model = new ModelMap();
		
		if(ComUtil.isEmpty(mobile)){
			model.put("success", false);
			model.put("msg", "手机号码不能为空！");
			return model;
		}
		if(ComUtil.isEmpty(xcode)){
			model.put("success", false);
			model.put("msg", "验证码不能为空");
			return model;
		}
		//判断是否频繁发送短信
		RunfastSmsSendrecord record = smsSendRecordService.findNewRecord(mobile, 2,xcode);
		if(record==null||record.getSendtime()==null
				||(System.currentTimeMillis()-record.getSendtime().getTime()>60000)){
			model.put("success", false);
			model.put("msg", "验证码超过了6分钟无效");
			return model;
		}
	
		RunfastShopper shopper = shopperService.findByNumeber(mobile);
		if(shopper.equals(null)){
			model.put("success", false);
			model.put("msg", "该号码尚未注册");
			return model;
		}
		shopperService.updatepassword(shopper);
		String content ="您的登录密码："+shopper.getPassword()+"请妥善保管！";
		//保存验证码记录
		record = new RunfastSmsSendrecord();
		record.setSmstype(2);
		record.setPhone(mobile);
		record.setIpaddr(request.getRemoteAddr());
		record.setMsg(content);
		record.setSendtime(new Date());
		smsSendRecordService.insert(record);
		ModelMap sendMsg = SingleSendSms.sendMsg(mobile, "{'code':'123321'}", "SMS_47920224");
		if(!(boolean)sendMsg.get("success")){
			sendMsg.put("msg",sendMsg.get("message"));
			return sendMsg;
		}
		
		System.out.println("骑手找回密码"+content);

		model.put("success", true);
		model.put("msg", "您的密码正发送到手机上，请注意查看！");
		return model;
	}

	private Map<String,Object> checkVersion(Integer vercode,String verFile){

		Map<String,Object> obj = new HashMap<String, Object>();
		boolean isupdate = false;

		if(vercode==null){
			isupdate = true;
		}else{
			File file = new File(verFile);
			if(file.exists()){
				try {
					BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
					StringBuilder sb = new StringBuilder();
					String tmp = br.readLine();
					while(tmp!=null){
						sb.append(tmp).append("\n");
						tmp = br.readLine();
					}
					System.out.println("sb="+sb.toString());
					String[] args = sb.toString().split("\\|");
					if(args.length==4){
						System.out.println("args[0]="+args[0]+"bver="+vercode);
						if(vercode<(ComUtil.getInt(args[0]))){
							isupdate = true;
							obj.put("apkName", args[2]);
							obj.put("msg", args[3]);
						}
					}
					br.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}

		obj.put("isupdate", isupdate);

		return obj;
	}
	/**
	 *  安卓版本判断
	 * @param vercode
	 * @param verFile
	 * @return
	 */
	private Map<String,Object> checkAndroidVersion(Integer vercode,String verFile){
		
		Map<String,Object> obj = new HashMap<String, Object>();
		boolean isupdate = false;
		
		if(vercode==null){
			isupdate = true;
		}else{
			File file = new File(verFile);
			if(file.exists()){
				try {
					BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
					StringBuilder sb = new StringBuilder();
					String tmp = br.readLine();
					while(tmp!=null){
						sb.append(tmp).append("\n");
						tmp = br.readLine();
					}
					System.out.println("sb="+sb.toString());
					String[] args = sb.toString().split("\\|");
					if(args.length==4){
						System.out.println("args[0]="+args[0]+"bver="+vercode);
						if(vercode<(ComUtil.getInt(args[0]))){ //安桌的版本比较
							isupdate = true;
							obj.put("apkName", args[2]);//apkName的名字
							obj.put("msg", args[3]);//内容
						}
					}
					br.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
		
		obj.put("isupdate", isupdate);
		
		return obj;
	}

	/**
	 * ios版本判断
	 * @param vercode
	 * @param verFile
	 * @return
	 */
	private Map<String,Object> checkIOSVersion(Integer vercode,String verFile){
		
		Map<String,Object> obj = new HashMap<String, Object>();
		boolean isupdate = false;
		
		if(vercode==null){
			isupdate = true;
		}else{
			File file = new File(verFile);
			if(file.exists()){
				try {
					BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
					StringBuilder sb = new StringBuilder();
					String tmp = br.readLine();
					while(tmp!=null){
						sb.append(tmp).append("\n");
						tmp = br.readLine();
					}
					System.out.println("ios,sb="+sb.toString());
					String[] args = sb.toString().split("\\|");
					if(args.length==3){
						System.out.println("args[0]="+args[0]+"bver="+vercode);
						if(vercode<(ComUtil.getInt(args[0]))){
							isupdate = true;
							obj.put("msg", args[2]);
						}
					}
					br.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
		
		obj.put("isupdate", isupdate);
		
		return obj;
	}
	
}
